package com.cash.loan.modular.cash.annotation.support;

import com.cash.loan.common.entity.UserInfo;
import com.cash.loan.modular.cash.annotation.PvUvLog;
import com.cash.loan.modular.cash.service.StatisticsPvUvService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * @author Administrator
 * @Date 2018-07-11 9:30
 */
@Component
@Aspect
public class PvUvSupport {

    private static Logger logger = LoggerFactory.getLogger(PvUvSupport.class);

    @Autowired
    private StatisticsPvUvService pvUvService;

    @Pointcut("@annotation(com.cash.loan.modular.cash.annotation.PvUvLog)")
    private void pvUvLog() {
    }

    @Around("pvUvLog()")
    public Object statisticsPvAndUv(ProceedingJoinPoint point) throws Throwable {
        //环绕增强的前置处理，该类无需实现
        //先执行业务
        Object result = point.proceed();
        //执行统计,环绕增强的后置处理
        try {
            this.handle(point);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("统计点击量出错",e.getMessage());
        }
        return result;
    }

    /**
     * 统计功能实现
     * @param point
     * @throws Exception
     */
    private void handle(ProceedingJoinPoint point) throws Exception {
        Object[] args = point.getArgs();

        Long productId = null;
        UserInfo userInfo = new UserInfo();

        if(args[0] != null) {
            productId = Long.valueOf((Integer) args[0]);
        }

        if(args[2] != null) {
            userInfo = (UserInfo) args[2];
        }

        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        PvUvLog pvUvLog = method.getAnnotation(PvUvLog.class);

        Integer type = Integer.valueOf(pvUvLog.type());

        pvUvService.statisticsPvUv(userInfo,productId, type);
    }
}
